const User = require('../model/user.model')
const UserDeatil = require('../model/user_detail.model')
const { Op, Sequelize } = require("sequelize");
const { raw } = require('express');
class UserManageService {

    // 查询所有用户
    async usermanage({ username, is_admin, createdAtFrom, createdAtTo, updatedAtFrom, updatedAtTo, currentPage, pageSize,is_delete }) {
        User.belongsTo(UserDeatil, { foreignKey: 'user_id', targetKey: 'user_id' })
        const where = {};
        username && (where['username'] = {
            [Op.like]: `%${username}%`
        })
        is_admin && (where['is_admin'] = {
            [Op.eq]: is_admin
        })
        createdAtFrom && (where['createdAt'] = {
            [Op.between]: [createdAtFrom, createdAtTo]
        })
        updatedAtFrom && (where['updatedAt'] = {
            [Op.between]: [updatedAtFrom, updatedAtTo]
        })
        is_delete && (where['is_delete'] = {
            [Op.eq]: is_delete
        })
        const { count, rows } = await User.findAndCountAll({
            where,
            offset: (currentPage - 1) * pageSize,
            limit: Number(pageSize),
            attributes: [Sequelize.col('UserDetail.email'), Sequelize.col('UserDetail.phone'), Sequelize.col('UserDetail.job'), Sequelize.col('UserDetail.tag'),
            Sequelize.col('User.username'), Sequelize.col('User.id'), Sequelize.col('User.user_id'), Sequelize.col('User.is_admin'), Sequelize.col('User.user_img'),
            Sequelize.col('User.createdAt'), Sequelize.col('User.updatedAt'),Sequelize.col('User.is_delete')],
            include: [{
                model: UserDeatil,
                as: 'UserDetail',
                attributes: [],
            },
            ],
            raw: true
        });
        return rows ? { data: rows, total: count } : { error: 500 }
    }
    // 更新用户
    async updateuserService(param) {
        const { user_id, is_admin, is_delete } = param
        console.log(user_id, is_admin, is_delete)
        let obj = {}
        is_admin && (obj['is_admin'] = is_admin)
        obj['is_delete'] = is_delete
        console.log(obj)
        const res = await User.update(obj, {
            where: {
                user_id: user_id,
            }
        })
        console.log(res,'🚀')
        return res[0] > 0 ? 'success' : 'error'
    }
}
// 导出后 在控制器controller中使用
module.exports = new UserManageService()